//
//  BNRItemStore.m
//  Quiz
//
//  Created by YaoJacob on 15/11/3.
//  Copyright © 2015年 Roger. All rights reserved.
//

#import "BNRItemStore.h"
#import "BNRItem.h"
#import "BNRImageStore.h"

@interface BNRItemStore ()
@property (nonatomic) NSMutableArray * privateItems; //天不知道
@end

@implementation BNRItemStore
//单体 begin
+(instancetype)sharedStore
{
    static BNRItemStore* sharedStore = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedStore = [[self alloc]initPrivate];
    });
    //    if (!sharedStore) {
    //        sharedStore = [[self alloc]initPrivate];
    //    }
    
    return sharedStore;
}

-(instancetype)init
{
    @throw [NSException exceptionWithName:@"Single" reason:@"use + [BNRItemStore sharedStore]" userInfo:nil];
    return nil;
}

-(instancetype)initPrivate
{
    self = [super init];
    if (self) {
        //self.privateItems = [[NSMutableArray alloc]init];
        NSString* path = [self itemArchivePath];
        _privateItems = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        
        if (!_privateItems) {
            _privateItems  = [[NSMutableArray alloc]init];
        }
    }
    return self;
}
//单体 end
-(NSArray*)allItems
{
    return [self privateItems];//不用copy
}

-(BNRItem*)CreateItem
{
    BNRItem* item = [BNRItem randomItem];
    [self.privateItems addObject:item];
    
    return item;
}


-(void)removeItem:(BNRItem*)item
{
    [[BNRImageStore sharedStore]deleteImageForKey:item.itemKey];
    [self.privateItems removeObjectIdenticalTo:item];
    
}

-(void)moveItemAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex
{
    if (toIndex == fromIndex) {
        return;
    }
    
    BNRItem* fromItem = self.privateItems[fromIndex];
    [self.privateItems removeObjectAtIndex:fromIndex];
    
    [self.privateItems insertObject:fromItem atIndex:toIndex];
}

#pragma Archive
-(NSString*)itemArchivePath
{
    return [self itemArchivePathForFile:@"items.archive"];
}

-(NSString*)itemArchivePathForFile:(NSString*)fileName
{
    NSArray *documentDirectorys = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString * documentDirectory = [documentDirectorys firstObject];
    NSString * fullPath = [documentDirectory stringByAppendingString:fileName];
    
    NSLog(@"archive Path:  %@", fullPath);
    return fullPath;
}

-(BOOL)saveChanges
{
    NSString *path = [self itemArchivePath];
    
    return [NSKeyedArchiver archiveRootObject:self.privateItems toFile:path];
}
@end
